package com.feng.ems.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.ems.bean.Book;
import com.feng.ems.service.BookService;
import com.feng.ems.service.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    BookServiceImpl bookService;

    @GetMapping("/login")
    public String toLoginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String LoginValidation(Book book,
                                  RedirectAttributes redirectAttributes,
                                  Model model,
                                  HttpSession session){
        String name = book.getName();
        String password = book.getPassword();
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("password",password);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("name",name );
        queryWrapper.ge("password",password);
        Book one = bookService.getOne(queryWrapper);
//        if (one.toString()!=null){
        if (one!=null){
//        if (!StringUtils.isEmpty(one.toString())){
            /**
             * org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'records' cannot be found on null
             * 如果直接从登录界面进入这个页面是错误的，因为这里用到了showemp这个请求的page分页查询的数据，直接进入是没有查询的，page分页数据为null
             * 所以只能先发送showemp请求查询到page分页数据才能成功的到达main页面。
             */
//            return "redirect:/main";
            session.setAttribute("login",name);
            //模拟服务器错误：5xx.html测试
//            int a = 12/0;
//            return "redirect:/showemp";
            return "redirect:/main";
        }
        String msg = "账号或密码错误";
        model.addAttribute("msg",msg);
        return "login";
    }

    @GetMapping("/main")
    public String toMainPage(){
        return "main";
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @GetMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "redirect:/login";
    }
}
